var msgDAO = require('../models/message.js');
var deviceInfoDAO = require('../models/deviceInfo');

var message = {
				msgId : 'bbb',
				msgType: 'msg.messageType',
				title : 'msg.title',
				target: 'deviceId',
				receive: false,
				extras: {"moduleIdentifer":"com.foss.announcement"},
				createTime:new Date(),
				// receiveTime: new Date()
			}
			
// save			
/*msgDAO.save(message, function(err) {
	if(err)
		console.log(err);
	else 
		console.log("成功！！！");
});
console.log('asas');*/

//  update
/*var conditions = {msgId: 'bbb'},
	update = {
		receive: true, 
		receiveTime: new Date()
	};

msgDAO.findOneAndUpdate(conditions, update, function(err, Message){
	console.log(Message);
});
*/

/*var userInfo = {"appName":"com.foreveross.pushsdk.demo","deivceName":"GT-I9000","deviceId":"3BC9C61C7E0A631AC1A739152FB796AF",
	 "osVersion":"4.2.2","pushToken":"3112ea3c-62c7-4b2e-b44a-eb6537f5964b","tags":[{"key":"platform","value":"android"},{"key":"role","value":"tester"}],
	"userName":"pushTest"};
// console.log(userInfo.deviceId);
// console.log(typeof userInfo.deviceId);

var conditions = {deviceId: userInfo.deviceId.toString()},
				update = {
					online: true, 
					connectTime: new Date()
				};
deviceInfoDAO.findOneAndUpdate(conditions, update, function(err, deviceInfo) {
	if(err) {
		console.error('mongodb operate exception...\n' + err);
	} else {
		if (deviceInfo) {
			console.log('更新签到状态成功，' + deviceInfo.deviceId + ', deviceInfo.online=' + deviceInfo.online);
		} else {
			deviceInfoDAO.save(userInfo, function(err) {
				if(!err) {
					console.log('签到成功，deviceInfo.deviceId=' + deviceInfo.deviceId);
				}
			});								
		}
	}
});*/


// find
/*msgDAO.findByName({msgId: 'aaa'}, function(err, obj) {
	if(err) console.log(err);
	console.log(obj);
});*/


/*msgDAO.query({receive: false}, function(err, message) {
	console.log('设备' + (message ? "有" : '没有') + '离线消息');
	if(!err && message) {
		// console.log('开始发送离线信息：\n'+ message);
		// console.log(message instanceof Array);
		message.forEach(function(item, index, array){
			console.log(item);
		});
		// connection.write(msgpack.packWithType(message, 1)); // 发送整个消息，等待设备回执
	} 
});*/

msgDAO.update({receive: true}, {receive: false, receiveTime: Date.now()}, {/*safe: false,*/ multi: true}, function(err, numberAffected, message) {
	if (err) return handleError(err);
  console.log('The number of updated documents was %d', numberAffected);
  console.log('The raw response from Mongo was ', message);
});